import { memo, useCallback, useState } from "react";
import { Input, Table, Image, Button, Space } from "antd";
import styles from "./index.module.css";
import Buttons from "../../components/button";
import Radios from "../../components/Radio";
import { ButtonChangePorps, ButtonItem } from "../../type/button";
import { RadioChangeValue } from "../../type/radio";
import type { ColumnsType } from "antd/es/table";
import { BaseTableColumns, createOrUpdateData } from "../../type/active";
import { useFetchTableList } from "../../hooks/use-fetch-table-list";
import { getTableData, delTableData, createData, getActiveEditData } from "../../api/active";
import _ from "lodash";
import { useDeleteTable } from "../../hooks/use-delete-table";
import ModalFrom from "../../components/modalForm";
import { useCreate } from "../../hooks/use-table-create";
import { Key } from "antd/es/table/interface";
import { changeTime } from "../../untils/date";

const Index = () => {
  const [open, setOpen] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>("新增");
  const [detailid, setDetailid] = useState<number>(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [editData, setEditData] = useState<any>({});

  const { setParams } = useCreate({
    API: createData,
  });
  const { dataSource, total, filterParams, setFilterParams } =
    useFetchTableList({
      API: getTableData,
    });
  const { setDeleteProps, deleteTable } = useDeleteTable({
    API: delTableData,
    title: "就是要删除你呢",
    success: () => {
      setSelectedRowKeys([]);
      // 根据业务逻辑 删除成功以后要重置分页参数为1
      setFilterParams({ ...filterParams, page: 1 });
    },
  });
  const buttonList: ButtonItem[] = [
    {
      type: "primary",
      label: "新增",
      danger: false,
      disabled: false,
    },
    {
      type: "default",
      label: "刷新",

      disabled: false,
      danger: false,
    },
    {
      type: "primary",
      danger: true,
      disabled: selectedRowKeys.length===0,
      label: "删除",
    },
  ];
  const radioList = [
    {
      label: "全部",
      value: "",
    },
    {
      label: "未开始",
      value: "0",
    },
    {
      label: "进行中",
      value: "1",
    },
    {
      label: "已结束",
      value: "2",
    },
  ];
  const radioChange = (value: RadioChangeValue) => {
    setFilterParams({
      ...filterParams,
      activeStatus: value,
      page: 1,
    } as any);
  };
  const columns: ColumnsType<BaseTableColumns> = [
    {
      title: "活动名称",
      dataIndex: "activeName",
      key: "id",
      width: 200,
    },
    {
      title: "活动封面",
      dataIndex: "activeImgUrl",
      key: "id",
      width: 100,
      render: (text) => {
        return <Image width={50} src={text} key={text} />;
      },
    },
    {
      title: "活动状态",
      dataIndex: "activeStatus",
      width: 120,
      key: "id",
      render: (text) => renderActiveStatus(text),
    },
    {
      title: "活动上限",
      dataIndex: "activeMax",
      width: 100,
      key: "id",
    },
    {
      title: "报名人数",
      dataIndex: "applicants",
      width: 100,
      key: "id",
    },
    {
      title: "活动时间",
      dataIndex: "activeStartTime",
      width: 200,
      key: "id",
      render: (text, item) => {
        return `${item.activeStartTime} - ${item.activeEndTime}`;
      },
    },
    {
      title: "主办方",
      dataIndex: "business",
      key: "id",
      width: 150,
    },
    {
      title: "操作",
      dataIndex: "",
      key: "id",
      render: (text, item) => {
        return (
          <Space>
            <Button type="primary" onClick={() => handleClickEdit(item)}>
              编辑
            </Button>
            <Button
              danger
              onClick={() => {
                console.log(item,"item")
                deleteTable([item.key.toString()]);
              }}
            >
              删除
            </Button>
            <Button>查看报名人数</Button>
          </Space>
        );
      },
    },
  ];
  const FormFiledList = [
    {
      type: "Input",
      name: "activeName",
      label: "活动名称",
      required: true,
      message: "请输入活动名称",
    },
    {
      type: "Input",
      name: "activeMax",
      label: "活动上限",
    },
    {
      type: "DatePicker",
      name: "activeTime",
      label: "活动时间",
    },
    {
      type: "Input",
      name: "business",
      label: "主办方",
    },
    {
      type: "Image",
      name: "activeImgUrl",
      label: "活动封面",
    },
    {
      type: "Input",
      name: "activeDetail",
      label: "活动详情",
    },
  ];
  // tab 按钮点击
  const onButtonChange = (keys: ButtonChangePorps) => {
    const { value } = keys;
    if (value === "删除") {
      const changeDeleteProps = selectedRowKeys.map((ite: any) =>
        ite.toString()
      );
      setDeleteProps(changeDeleteProps);
    } else if (value === "刷新") {
      setFilterParams({
        page: 1,
      } as any);
    } else if (value === "新增") {
      showModal();
    }
  };
  // 编辑
  const handleClickEdit = async (item: any) => {
    showModal("编辑");
    let result= await getActiveEditData({ editId: item.key });
    setDetailid(item.key);
    setEditData(result.data)
  };
  // formate table
  const renderActiveStatus = (text: string) => {
    if (text.toString() === "0") {
      return "未开始";
    } else if (text.toString() === "1") {
      return "进行中";
    } else if (text.toString() === "2") {
      return "已结束";
    }
  };
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  // 输入框检索
  const inputSearch = useCallback(
    _.debounce((e: any) => {
      setFilterParams({
        ...filterParams,
        activeName: e.target.value,
        page: 1,
      } as any);
    }, 300),
    []
  );
  // 弹框点击部分
  const showModal = (title: string = "") => {
    setOpen(true);
    const modalTitle = title ? title : "新增";
    setModalTitle(modalTitle);
  };
  const closeModal = () => {
    setOpen(false);
    setDetailid(0);
  };
  const onOk = async (val: createOrUpdateData) => {
    const { activeTime } = val;
    if (!activeTime) {
      return  setParams(val)
    };
    const res = changeTime(activeTime[0], activeTime[1], "YYYY-MM-DD");
    const params = { ...val, activeTime: res };
    setParams(params);
  };
  return (
    <div>
      <div className={styles.activeContainer}>
        <Buttons
          buttonConfig={buttonList}
          onChange={(buttonChangeProp: ButtonChangePorps) =>
            onButtonChange(buttonChangeProp)
          }
        />
        <Radios list={radioList} onChange={(value) => radioChange(value)} />
        <Input
          placeholder="请输入活动名称"
          className={styles.activeInput}
          onChange={inputSearch}
        />
      </div>
      <Table
        rowSelection={rowSelection}
        columns={columns}
        rowKey={(record) => record.key}
        dataSource={dataSource}
        style={{ marginTop: "20px" }}
        pagination={{
          total,
          pageSize: filterParams.pageSize,
          current: filterParams.page,
          onChange: (page) => {
            setFilterParams({
              ...filterParams,
              page,
            });
          },
        }}
      />
      <ModalFrom
        close={closeModal}
        onOk={(val) => onOk(val)}
        FormFiledList={FormFiledList}
        detailid={detailid}
        modalTitle={modalTitle}
        editData={editData}
        openModalFlag={open}
      />
    </div>
  );
};
export default memo(Index);
